package life.system.product.service.impl;

import com.mysql.cj.util.StringUtils;
import life.system.common.constant.ProductConstant;
import life.system.common.to.es.SkuEsModel;
import life.system.common.utils.R;
import life.system.common.vo.SkuInfoVo;
import life.system.product.entity.*;
import life.system.product.feign.SearchFeignService;
import life.system.product.service.*;
import life.system.product.vo.SkuDetailResult;
import life.system.product.vo.SkuSaveVo;
import life.system.product.vo.Skus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import life.system.common.utils.PageUtils;
import life.system.common.utils.Query;

import life.system.product.dao.SkuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SkuInfoDescService skuInfoDescService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private CityService cityService;
    @Autowired
    private SortService sortService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<>()
        );
        return new PageUtils(page);
    }

    /**
     * 保存
     */
    @Transactional
    public void saveSpuInfo(SkuSaveVo vo) {

        // 1、保存商品信息
        SkuInfoEntity skuInfo = new SkuInfoEntity();
        skuInfo.setTitle(vo.getTitle());
        skuInfo.setSubtitle(vo.getSubtitle());
        skuInfo.setCityId(vo.getCityId());
        skuInfo.setAddress(vo.getAddress());
        skuInfo.setLng(vo.getLng());
        skuInfo.setLat(vo.getLat());
        skuInfo.setPublishStatus(vo.getPublishStatus());
        skuInfo.setSortId(vo.getSortId());
        skuInfo.setCreateTime(new Date());
        for (Skus skus : vo.getSkus()) {
            skuInfo.setPrice(skus.getPrice());
        }
        this.save(skuInfo);

        // 2、保存SKU的描述图片
        List<String> decript = vo.getDecript();
        SkuInfoDescEntity descEntity = new SkuInfoDescEntity();
        descEntity.setSkuId(skuInfo.getId());
        descEntity.setDecript(String.join(",", decript));
        skuInfoDescService.save(descEntity);


        // 3、保存SKU的轮播图
        List<Skus> skus = vo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(item -> {
                // 3.1、 sku的图片信息
                Long skuId = skuInfo.getId();
                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> {
                    // 返回true就是需要，false就是剔除
                    return !StringUtils.isNullOrEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(imagesEntities);

            });
        }

    }

    /**
     * 商品上架
     */
    public void up(Long skuId) {

        SkuEsModel esModel = new SkuEsModel();

        // 1、获取商家的基本信息
        SkuInfoEntity skuInfoEntity = this.getById(skuId);

        // 2、获取商家的所属城市
        CityEntity cityEntity = cityService.getById(skuInfoEntity.getCityId());

        // 3、获取商家的所属分类
        SortEntity sortEntity = sortService.getById(skuInfoEntity.getSortId());

        // 4、获取商家的默认图片
        SkuImagesEntity skuImages = skuImagesService.getOne(new QueryWrapper<SkuImagesEntity>().eq("sku_id", skuId).eq("default_img", 1));

        esModel.setId(skuInfoEntity.getId());
        esModel.setTitle(skuInfoEntity.getTitle());
        esModel.setSubtitle(skuInfoEntity.getSubtitle());
        esModel.setPrice(skuInfoEntity.getPrice());
        esModel.setCityId(cityEntity.getId());
        esModel.setCityName(cityEntity.getName());
        esModel.setSortId(sortEntity.getId());
        esModel.setSortName(sortEntity.getName());
        if (skuImages.getImgUrl() != null) {
            esModel.setImgUrl(skuImages.getImgUrl());
        }


        R r = searchFeignService.productStatusUp(esModel);
        if (r.getCode() == 0) {
            // 远程调用成功
            //  6、修改当前spu的状态 上架
            skuInfoEntity.setPublishStatus(ProductConstant.StatusEnum.SPU_UP.getCode());
            this.updateById(skuInfoEntity);
        }

    }


    /**
     * 删除
     */
    @Transactional
    public void productRemoveByIds(Integer[] ids) {

        for (Integer id : ids) {
            //  1、删除elasticsearch中文档
            R r = searchFeignService.productDel(id);
            if (r.getCode() == 0) {
                //  2、删除轮播图中数据
                skuImagesService.remove(new QueryWrapper<SkuImagesEntity>().eq("sku_id", id));

                //  3、删除介绍图中的数据
                skuInfoDescService.remove(new QueryWrapper<SkuInfoDescEntity>().eq("sku_id", id));

                //  4、删除商品中数据
                this.removeById(id);
            }
        }
    }



    public SkuDetailResult detail(Long skuId) {
        SkuDetailResult result = new SkuDetailResult();

        // 1、查询skuId的信息
        SkuInfoEntity skuInfo = this.getById(skuId);

        List<String> imgUrl = new ArrayList<>();
        // 2、查询skuId的轮播图信息
        List<SkuImagesEntity> list = skuImagesService.list(new QueryWrapper<SkuImagesEntity>().eq("sku_id", skuId));
        for (SkuImagesEntity skuImagesEntity : list) {
            imgUrl.add(skuImagesEntity.getImgUrl());
        }

        // 3、查询skuId的介绍图片的信息
        SkuInfoDescEntity infoDesc = skuInfoDescService.getOne(new QueryWrapper<SkuInfoDescEntity>().eq("sku_id", skuId));
        String[] split = infoDesc.getDecript().split(",");

        result.setId(skuInfo.getId());
        result.setImgUrl(imgUrl);
        result.setTitle(skuInfo.getTitle());
        result.setSubtitle(skuInfo.getSubtitle());
        result.setPrice(skuInfo.getPrice());
        result.setAddress(skuInfo.getAddress());
        result.setLng(skuInfo.getLng());
        result.setLat(skuInfo.getLat());
        result.setDecripts(Arrays.asList(split));

        return result;
    }

    @Override
    public SkuInfoVo getBySkuId(Long id) {
        SkuInfoVo skuInfoVo = new SkuInfoVo();
        SkuInfoEntity skuInfo = this.getById(id);
        // 4、获取商家的默认图片
        SkuImagesEntity skuImages = skuImagesService.getOne(new QueryWrapper<SkuImagesEntity>().eq("sku_id",id).eq("default_img", 1));

        skuInfoVo.setId(id);
        skuInfoVo.setTitle(skuInfo.getTitle());
        skuInfoVo.setPrice(skuInfo.getPrice());
        skuInfoVo.setSkuDefaultImg(skuImages.getImgUrl());
        return skuInfoVo;
    }

}